package com.azdebugit.suanfa.test.niu;

public class NewtonIterator {

    public static void main(String[] args) {
        double x = 50, precision = 0.000000001;
        int maxcyc = 100;
        NewtonIterator newtonIterator = new NewtonIterator();
        if (newtonIterator.newton(x, precision, maxcyc) == 1) {
            System.out.println("该值附近的根为" + result + " 迭代次数 ： " + num);
        } else {
            System.out.println("迭代失败！");
            //2.648936536183
            //2.6489365361820902
        }
    }

    private static double result;
    private static int num;

    public double func(double x) { //函数
        return x * x * x * x - 3 * x * x * x + 1.5 * x * x - 4.0;
    }

    public double func1(double x) {//导数
        return 4 * x * x * x - 9 * x * x + 3 * x;
    }

    public int newton(double x, double precision, int maxcyc) {//迭代次数

        double x1, x0;
        int k;
        x0 = x;

        for (k = 0; k < maxcyc; k++) {
            if (func1(x0) == 0.0) {
                System.out.println("迭代过程中导数为0！");
                return 0;
            }

            x1 = x0 - func(x0) / func1(x0);  //牛顿迭代计算关系式，x1是是曲线过点(x0,f(x0))做切线，相交于x轴上的横坐标
            if (Math.abs(x1 - x0) < precision || Math.abs(func(x1)) < precision) {//精度判断，达到精度就结束迭代
                result = x1;
                num = k + 1;
                return 1;
            } else {
                x0 = x1;
            }
        }

        System.out.println("迭代次数超过预期!");
        return 0;
    }
}